﻿using System.Collections.Generic;
using xTeam.Glgcx.CommonUtilities;
using System.Linq;
using System;
using ShopB2C.Core.Helpers;

namespace xTeam.Glgcx.DataAccess
{
    public class ClassifyDataAccess
    {
        private GlgcxDataBase _dataBase;
        private List<EClassify> _classifyList;

        public ClassifyDataAccess()
        {

            _dataBase = new GlgcxDataBase();
            _classifyList = _dataBase.Classify.ToList();
            BuildClassTree();
        }

        public List<EClassify> GetClassifyList(string moduleKey)
        {


            return _dataBase.Classify.AsEnumerable()
                .Where(i =>
                    string.IsNullOrEmpty(moduleKey)
                    || i.ModuleKey.ToUpper() == moduleKey.ToUpper())
                    .OrderBy(i => i.Sequence).ToList();

        }

        public EClassify GetClassifyById(int classifyId)
        {

            return _dataBase.Classify.FirstOrDefault(i => i.ClassifyId == classifyId);

        }

        public int Delete(int classifyId)
        {
            int result = 0;

            var classify = this.GetClassifyById(classifyId);
            if (classify != null)
            {
                // _dataBase.DeleteObject(classify);
                _dataBase.Classify.Remove(classify);
                result = _dataBase.SaveChanges();

            }

            return result;
        }

        public int Update(EClassify entity)
        {
            int result = 0;

            var classify = _dataBase.Classify.FirstOrDefault(i => i.ClassifyId == entity.ClassifyId);

            bool isNew = classify == null;
            if (isNew)
                classify = new EClassify();

            classify.Childs = entity.Childs;
            classify.ClassifyId = entity.ClassifyId;
            classify.Description = entity.Description;
            classify.ETag = entity.ETag;
            classify.Floor = entity.Floor;
            classify.KeyWords = entity.KeyWords;
            classify.Redirect = entity.Redirect;
            classify.ModuleKey = entity.ModuleKey;
            classify.Sequence = entity.Sequence;
            classify.Title = entity.Title;
            classify.ParentId = entity.ParentId;
            classify.Path = entity.Path;

            if (isNew)
                _dataBase.Classify.Add(classify);

            this.UpdatePathAndFloor();

            result = _dataBase.SaveChanges();


            return result;
        }
        /// <summary>
        /// 更新层级和path
        /// </summary>
        private void UpdatePathAndFloor()
        {
            var classifyList = _dataBase.Classify.AsEnumerable();

            // 更新子数量
            classifyList.Select(i =>
                {
                    i.Childs = _dataBase.Classify.Count(ii => ii.ParentId == i.ClassifyId);
                    return true;
                }).ToList();

            ////// 更新Path
            //Action<EClassify> pathsTree = null;
            //pathsTree = (EClassify parent) =>
            //    {
            //        var childsList = classifyList.Where(i => i.ParentId == parent.ClassifyId);
            //        foreach (var child in childsList)
            //        {
            //            child.Path = string.Format("-{0}-{1}", parent.Path, parent.ClassifyId);
            //            child.Path = child.Path.Trim('-');
            //            child.Floor = child.Path.Split('-').Length;
            //            pathsTree(child);
            //        }
            //    };


            //Action<EClassify> tree = null;
            //tree = (EClassify query) =>
            //{
            //    var parent = classifyList.FirstOrDefault(p => p.ClassifyId == query.ParentId);
            //    if (parent != null)
            //        tree(parent);
            //    query.Path = string.Empty;
            //    query.Floor = 0;
            //    pathsTree(query);
            //};
            //foreach (var classify in classifyList.Where(i => i.Childs < 1))
            //    tree(classify);


        }

        public EClassify GetClassifyByTagName(string eTag)
        {

            var cls = _dataBase.Classify.FirstOrDefault(i => i.ETag == eTag);
            if (cls != null)
            {

                cls.Descendant = _dataBase.Classify.Where(i => i.ParentId == cls.ClassifyId).ToList();
                cls.Descendant.Add(cls);
            }

            return cls;

        }

        public EClassify GetClassifyByPinYinTagName(string eTag)
        {

            var cls = _dataBase.Classify.AsEnumerable()
                     .FirstOrDefault(i => ChineseCharHelper.ConvertToPinYin(i.ETag) == eTag);
            if (cls != null)
            {
                cls.Descendant = _dataBase.Classify.Where(i => i.ParentId == cls.ClassifyId).ToList();
                cls.Descendant.Add(cls);
            }
            return cls;

        }

        public EClassify GetClassifyETag(string tagName, string moduleKey)
        {

            return _dataBase.Classify.Where(i =>
                i.ETag.ToUpper() == tagName.ToUpper()
                && i.ModuleKey.ToUpper() == moduleKey.ToUpper()).SingleOrDefault();

        }

        private void BuildClassTree()
        {
            foreach (var item in _classifyList)
            {
                item.ChildList = _classifyList.Where(i => i.ParentId == item.ClassifyId).ToList();
                item.Parent = _classifyList.Where(i => i.ClassifyId == item.ParentId).SingleOrDefault();
                item.Descendant = item.ChildList;
            }


        }
    }
}
